<template>
  <div class="main">
    <div class="filter-container">
      <template>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoods">添加商品</el-button>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseGoodsPackage" plain>添加套餐</el-button>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseBHS" plain>添加碧划算</el-button>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseBoxPackage" plain>增加箱起礼包</el-button>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseBoxRetail" plain>增加箱起零售</el-button>
        <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="chooseBoxYuncang" plain>增加箱起云仓</el-button>
      </template>
      <el-button v-if="formData.goodsList.length > 7" type="success" class="filter-item fr" :loading="btnLoading" @click="save">保 存</el-button>
    </div>
    <el-form :model="formData" size="medium" ref="form" label-width="0px">
      <el-table :data="formData.goodsList" v-loading="pageLoading" element-loading-text="给我一点时间">
        <el-table-column align="center" label="类型" width="120">
          <template slot-scope="scope">
            <span v-text="itemTypes[scope.row.goodsType-1]"></span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="展示图" width="100">
          <template slot-scope="scope">
            <div class="avatar-uploader">
              <label class="el-upload el-upload-text" style="width: 80px; height: 80px; line-height: 82px">
                <img v-if="scope.row.picUrl" :src="scope.row.picUrl" alt="">
                <i v-if="!scope.row.picUrl" class="el-icon-plus avatar-uploader-icon"></i>
                <input type="file" class="el-upload__input" accept="image/*" @change="uploadAttrImg(scope.row, $event)">
              </label>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="goodsName" min-width="100"></el-table-column>
        <el-table-column align="center" label="排序" prop="sort" width="150">
          <template slot-scope="scope">
            <el-input type="number" v-model.number="scope.row.sort" style="width: 100%"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <a href="javascript: void(0);" class="el-icon-remove" @click="delItem(scope.row, scope.$index)"></a>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div style="text-align: center; padding: 20px">
      <el-button type="success" @click="save" :loading="btnLoading">保 存</el-button>
    </div>
  </div>
</template>
<script>
import differenceBy from 'lodash/differenceBy'
export default {
  name: 'brandGoods',
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return{
      pageLoading: true,
      btnLoading: false,
      itemTypes: ['商品', '套餐', '碧划算', '箱起礼包', '箱起零售', '箱起云仓'],
      formData: {
        brandId: this.id,
        goodsList: []
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 选择碧划算商品
    chooseBHS () {
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 3).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected= this.formData.goodsList.filter(item => item.goodsType === 3).map(i => {
        return {
          goodsId: i.goodsId,
          title: i.goodsName,
          imageUrl: i.picUrl
        }
      });
      this.bhsGoodsChoose(count, selected).then(val => {
        let goodsList = this.formData.goodsList.filter(item => item.goodsType ===3);
        let needDelGoods = differenceBy(goodsList, val, 'goodsId');
        let needAddGoods = differenceBy(val, goodsList, 'goodsId');
        console.log('needDelGoods', needDelGoods)
        console.log('needAddGoods', needAddGoods)
        let ids = [];
        needDelGoods.map(item => {
          if(item.id){
            ids.push(item.id);
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelGoods, 'goodsId'));
          }).catch(err => {
            console.log(err);
          });
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelGoods, 'goodsId'));
        }
        needAddGoods.map(item => {
          this.formData.goodsList.push({
            goodsId: item.goodsId,
            goodsName: item.title,
            goodsType: 3,
            fromType: 0,
            picUrl: item.imageUrl,
            sort: ''
          })
        })
      }).catch(err => {
        this.formData.goodsList = this.formData.goodsList.filter(item => item.goodsType !==3);
      })
    },
    fetchData() {
      this.pageLoading = true
      this.request({
        url: `/manage-home-web/v5/brand/goods/list`,
        method: 'get',
        params: { brandId: this.id }
      }).then(({data}) => {
        this.formData.goodsList = data || []
        this.pageLoading = false
      }).catch(err => {
        console.log(err)
        this.pageLoading = false
      })
    },
    // 选择商品
    chooseGoods(){
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 1).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected= this.formData.goodsList.filter(item => item.goodsType === 1).map(i => {
        return {
          goodsId: i.goodsId,
          name: i.goodsName,
          image: i.picUrl
        }
      });
      this.goodsChoose({ count }, selected).then(val => {
        let goodsList = this.formData.goodsList.filter(item => item.goodsType ===1);
        let needDelGoods = differenceBy(goodsList, val, 'goodsId');
        let needAddGoods = differenceBy(val, goodsList, 'goodsId');
        let ids = [];
        needDelGoods.map(item => {
          if(item.id){
            ids.push(item.id);
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelGoods, 'goodsId'));
          }).catch(err => {
            console.log(err);
          });
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelGoods, 'goodsId'));
        }
        needAddGoods.map(item => {
          this.formData.goodsList.push({
            goodsId: item.goodsId,
            goodsName: item.name,
            goodsType: 1,
            fromType: 0,
            picUrl: item.image,
            sort: ''
          })
        })
      }).catch(err => {
        this.formData.goodsList = this.formData.goodsList.filter(item => item.goodsType !==1);
      });
    },
    // 选择箱起礼包
    chooseBoxPackage () {
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 4).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected = this.formData.goodsList.filter(item=>item.goodsType===4).map(item => {
        return {
          bonusGiftId: item.goodsId,
          name: item.goodsName,
          imageMain: item.picUrl
        }
      })
      this.boxPackageGet(selected, count).then(val => {
        val.map(i => {
          i.goodsId = i.bonusGiftId
        })
        let packageList = this.formData.goodsList.filter(item => item.goodsType === 4)
        let needDelPackage = differenceBy(packageList, val, 'goodsId')
        let needAddPackage = differenceBy(val, packageList, 'goodsId')

        let ids = [];
        needDelPackage.map(item => {
          if(item.id){
            ids.push(item.id)
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
          }).catch(err => {
            console.log(err)
          })
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
        }
        needAddPackage.map((item) => {
          this.formData.goodsList.push({
            goodsId: item.bonusGiftId,
            goodsName: item.name,
            goodsType: 4,
            fromType: 0,
            picUrl: item.imageMain,
            sort: ''
          })
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 选择箱起零售
    chooseBoxRetail () {
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 5).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected = this.formData.goodsList.filter(item=>item.goodsType===5).map(item => {
        return {
          seriesId: item.goodsId,
          seriesName: item.goodsName,
          img: item.picUrl
        }
      })
      this.brandChoose({count:count, seriesTypeStr:'0,2'}, selected).then(val => {
        val.map(i => {
          i.goodsId = i.seriesId
        })
        let packageList = this.formData.goodsList.filter(item => item.goodsType === 5)
        let needDelPackage = differenceBy(packageList, val, 'goodsId')
        let needAddPackage = differenceBy(val, packageList, 'goodsId')

        let ids = [];
        needDelPackage.map(item => {
          if(item.id){
            ids.push(item.id)
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
          }).catch(err => {
            console.log(err)
          })
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
        }
        needAddPackage.map((item) => {
          this.formData.goodsList.push({
            goodsId: item.seriesId,
            goodsName: item.seriesName,
            goodsType: 5,
            fromType: 0,
            picUrl: item.img,
            sort: ''
          })
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 选择箱起云仓
    chooseBoxYuncang () {
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 6).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected = this.formData.goodsList.filter(item=>item.goodsType===6).map(item => {
        return {
          seriesId: item.goodsId,
          seriesName: item.goodsName,
          img: item.picUrl
        }
      })
      this.brandChoose({count:count, seriesTypeStr:'3'}, selected).then(val => {
        val.map(i => {
          i.goodsId = i.seriesId
        })
        let packageList = this.formData.goodsList.filter(item => item.goodsType === 6)
        let needDelPackage = differenceBy(packageList, val, 'goodsId')
        let needAddPackage = differenceBy(val, packageList, 'goodsId')

        let ids = [];
        needDelPackage.map(item => {
          if(item.id){
            ids.push(item.id)
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
          }).catch(err => {
            console.log(err)
          })
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
        }
        needAddPackage.map((item) => {
          this.formData.goodsList.push({
            goodsId: item.seriesId,
            goodsName: item.seriesName,
            goodsType: 6,
            fromType: 0,
            picUrl: item.img,
            sort: ''
          })
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 选择套餐
    chooseGoodsPackage(){
      let count = (6 - this.formData.goodsList.filter(item => item.goodsType !== 2).length)
      if(count <= 0){
        this.$message.warning('最多选择6个商品或套餐')
        return
      }
      let selected = this.formData.goodsList.filter(item=>item.goodsType===2).map(item => {
        return {
          packageId: item.goodsId,
          name: item.goodsName,
          image: item.picUrl
        }
      });
      this.packageChoose({ count }, selected).then(val => {
        val.map(i => {
          i.goodsId = i.packageId
        })
        let packageList = this.formData.goodsList.filter(item => item.goodsType ===2);
        let needDelPackage = differenceBy(packageList, val, 'goodsId');
        let needAddPackage = differenceBy(val, packageList, 'goodsId');

        let ids = [];
        needDelPackage.map(item => {
          if(item.id){
            ids.push(item.id);
          }
        });

        if(ids.length){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {ids}
          }).then(() => {
            this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
          }).catch(err => {
            console.log(err);
          });
        }
        else{
          this.formData.goodsList = (differenceBy(this.formData.goodsList, needDelPackage, 'goodsId'));
        }

        needAddPackage.map((item) => {
          this.formData.goodsList.push({
            goodsId: item.goodsId,
            goodsName: item.name,
            goodsType: 2,
            fromType: 0,
            picUrl: item.image,
            sort: ''
          });
        });
      }).catch(err => {
        console.log(err)
      });
    },
    delItem(row, index){
      this.$confirm(row.id?`该删除将直接从数据库删除，确定要删除吗?`:`确定要删除吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(row.id){
          this.request({
            url: '/manage-home-web/v5/brand/goods/delete',
            method: 'delete',
            data: {
              ids: [row.id],
            }
          }).then(() => {
            this.formData.goodsList.splice(index, 1);
            this.$message.success('删除成功');
          }).catch(err => {
            console.log(err);
          });
        }
        else{
          this.formData.goodsList.splice(index, 1);
          this.$message.success('删除成功');
        }
      }).catch(err => {
        console.log(err);
      });
    },
    uploadAttrImg(item, event) {
      const file = event.target.files[0];
      this.picFileUpload(file, (res) => {
        this.$set(item, 'picUrl', this.replaceImgUrl(res.filePath));
      });
    },
    save() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        }

        this.btnLoading = true;
        this.request({
          url: '/manage-home-web/v5/brand/goods/save',
          method: 'post',
          data: this.formData
        }).then(() => {
          this.$message.success('保存成功');
          this.btnLoading = false;
          this.$router.push({ name: "brand" });
        }).catch(err => {
          this.btnLoading = false;
          console.log(err);
        });
      })
    }
  }
}
</script>